package com.buba.controller;

import com.buba.feign.UserFeign;
import com.buba.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserFeign userFeign;

    @GetMapping("/findUserById")
    public User findUserById(Integer id){
        return userFeign.findUserById(id);
    }
    @GetMapping("/findUserById2")
    public User findUserById2(Integer id){
        return userFeign.findUserById2(id);
    }
    @PostMapping("/findByUser")
    public User findByUser(@RequestBody User user){
        return userFeign.findByUser(user);
    }
//
//    @Autowired
//    private RestTemplate restTemplate;
//    @Autowired
//    private DiscoveryClient discoveryClient;
//
//    @Autowired
//    private LoadBalancerClient loadBalancerClient;
//    @GetMapping("/findUserById3")
//    public User findUserById3(@RequestParam Integer id){
//        String url = "http://client1/user/findUserById?id=2";
//        ResponseEntity<User> res = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<User>() {
//        });
//        return res.getBody();
//    }
//
//    @GetMapping("/findUserById2")
//    public User findUserById2(@RequestParam Integer id){
//        ServiceInstance serviceInstance = loadBalancerClient.choose("client1");
//        String instanceId = serviceInstance.getInstanceId();
//        String url = instanceId+"/user/findUserById?id=2";
//        System.out.println(url);
//        ResponseEntity<User> res = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<User>() {
//        });
//        return res.getBody();
//    }
//
//    @GetMapping("/findUserById")
//    public User findUserById(@RequestParam Integer id){
//        List<ServiceInstance> list = discoveryClient.getInstances("client1");
//        if(list.isEmpty()){
//            return null;
//        }
//        ServiceInstance serviceInstance = list.get(0);
//        String host = serviceInstance.getInstanceId();
//
//        String url = host+"/user/findUserById?id=2";
//        ResponseEntity<User> res = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<User>() {
//        });
//        return res.getBody();
//    }

}
